package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品分类
     */

    @PostMapping
    public R<String>add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加菜品分类成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(name = "page" ,required = false,defaultValue = "1")Integer page,
                                  @RequestParam(name = "pageSize",required = false,defaultValue = "10") Integer pageSize){

        //构造分页对象
        Page<Category> pageInfo=new Page<>(page,pageSize);
        //构造条件对象
        QueryWrapper<Category> queryWrapper=new QueryWrapper<>();
        //按sort升序排列，如果相同就按照update_time修改时间排序
        queryWrapper.orderByAsc("type").orderByAsc("sort").orderByDesc("update_time");
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除
     */

    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 修改
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return  R.success("修改成功");
    }

    /**
     * 根据type查询分类列表
     */

    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        //构造条件
        QueryWrapper <Category> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(type !=null,"type",type);
        //查询数据
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
